// FIXED:登录的功能：https://gitee.com/full-stack-interview/node-data-orm.git，文件夹：expressCros
// 如何拦截查看axios的请求日志
import { Alert, Button, StyleSheet, TextInput, View } from "react-native";
// LoginScreen.js
import React, { useState } from "react";

import apis from "./../../services/index";
import fetchapis from "./../../services/fetch";
// import axios from "axios";
import { useNavigation } from "@react-navigation/native";

/**
 * 测试案例内容
 * console.log(new Date().getMonth()+1,new Date().getDate()

 */
const urlPar = {
  // 大佬们，这个是我申请的聚合数据应用的key，每天只有100免费请求次数
  key: "7606e878163d494b376802115f30dd4e",
  v: "1.0",
  month: Number(new Date().getMonth() + 1),
  day: Number(new Date().getDate()),
};

const LoginScreen = () => {
  const navigation = useNavigation();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const handleLogin = async () => {
    try {
      // const response = await apis("http://172.16.31.203:5055/login", {
      const response = await apis(`${process.env.API_URL}/login`, {
        method: "post",
        data: {
          email,
          password,
        },
      }).then((res) => {
        // Alert.alert(JSON.stringify(res));
        if (res.data.success) {
          Alert.alert("Success2222222", res.data.message);
          setEmail("");
          setPassword("");
          navigation.navigate("testnavigate");
        } else {
          Alert.alert("Error1");
        }
      });
      // const response = await apis.post("/login", {
      //   email,
      //   password,
      // });
    } catch (error) {
      Alert.alert("Error2", "Something went wrong. Please try again.");
    }
  };

  const handleFetch = async () => {
    try {
      const response = await fetchapis("GET", "/japi/toh", {
        urlParams: urlPar,
      });
      console.log("fetch------response.data", response);

      Alert.alert("fetch------response.data", JSON.stringify(response));
    } catch (error) {
      Alert.alert("fetch-----error", "Something went wrong. Please try again.");
    }
  };

  return (
    <View style={styles.container}>
      <TextInput
        style={styles.input}
        placeholder="Email"
        value={email}
        onChangeText={setEmail}
      />
      <TextInput
        style={styles.input}
        placeholder="Password"
        secureTextEntry
        value={password}
        onChangeText={setPassword}
      />
      <Button title="Login" onPress={handleLogin} />
      <Button title="fetchApi" onPress={handleFetch} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    padding: 20,
  },
  input: {
    width: "100%",
    padding: 15,
    borderWidth: 1,
    borderColor: "#ddd",
    marginBottom: 15,
    borderRadius: 5,
  },
});

export default LoginScreen;
